//
//  FCRelationBindInfoSelectedTableViewCell.m
//  customerRelation_Example
//
//  Created by 陈文斌 on 2019/2/21.
//  Copyright © 2019 64912907. All rights reserved.
//

#import "FCRelationBindInfoSelectedTableViewCell.h"
#import "NSMutableAttributedString+FCReplaceString.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationTypeListModel.h"
#import "FCRelationTyleSheetViewController.h"
#import "UIViewController+runtimeCheck.h"
#import "UIViewController+returnBlock.h"
#import "FCChoiceEmpScrollView.h"
#import "CustomerRelationHeader.h"
#import "FCCrmSupplyRelationOnlyTypeManagerModel.h"

@interface FCRelationBindInfoSelectedTableViewCell ()
@property (nonatomic, strong) UIView *view;
@property (nonatomic, strong) NSMutableArray *relationTypeIdArr;
@property (nonatomic, strong) NSMutableArray *employeeIdArr;
@property (nonatomic, strong) FCChoiceEmpScrollView *employeeScrollView;
@property (nonatomic, strong) UIControl *relationEmployeeControl;
@property (nonatomic, strong) NSMutableArray *oldEmployeeArr;
@property (nonatomic, strong) UILabel *relationEmployeeValue;

@property (nonatomic, strong) NSMutableArray *manageRelationTypes;
@property (nonatomic, strong) NSMutableArray *relationTypes;
@property (nonatomic, strong) NSMutableArray *selectedRelationTypeArr;

@property (nonatomic, assign) BOOL isLoadData;

@end

@implementation FCRelationBindInfoSelectedTableViewCell
- (NSMutableArray *)selectedRelationTypeArr{
    if (!_selectedRelationTypeArr) {
        _selectedRelationTypeArr = [NSMutableArray array];
    }
    return _selectedRelationTypeArr;
}
- (NSMutableArray *)relationTypes{
    if (!_relationTypes) {
        _relationTypes = [NSMutableArray array];
    }
    return _relationTypes;
}
- (NSMutableArray *)manageRelationTypes{
    if (!_manageRelationTypes) {
        _manageRelationTypes = [NSMutableArray array];
    }
    return _manageRelationTypes;
}

- (NSMutableArray *)relationTypeIdArr{
    if (!_relationTypeIdArr) {
        _relationTypeIdArr = [NSMutableArray new];
    }
    return _relationTypeIdArr;
}
- (NSMutableArray *)employeeIdArr{
    if (!_employeeIdArr) {
        _employeeIdArr = [NSMutableArray new];
    }
    return _employeeIdArr;
}
- (NSMutableArray *)oldEmployeeArr{
    if (!_oldEmployeeArr) {
        _oldEmployeeArr = [NSMutableArray array];
    }
    return _oldEmployeeArr;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = UIColor.clearColor;
        _view = [UIView new];
        [self addSubview:_view];
        [_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.top.and.bottom.mas_equalTo(0);
        }];
        _view.backgroundColor = UIColor.whiteColor;
        
        // 上下游关系
        UIControl *relationTypeControl = [UIControl new];
        [_view addSubview:relationTypeControl];
        [relationTypeControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.left.and.right.mas_equalTo(0);
            make.height.mas_equalTo(44);
        }];
        [relationTypeControl addTarget:self action:@selector(getCacheData) forControlEvents:UIControlEventTouchUpInside];
        UILabel *relationType = [UILabel new];
        [relationTypeControl addSubview:relationType];
        [relationType mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.centerY.mas_equalTo(0);
//            make.width.mas_equalTo(100);
        }];
        relationType.font = font14;
        relationType.textColor = FCGrayTxtDetailColor;
        NSMutableAttributedString *string1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  ＊",customerRelationLocaChanged(@"上下游关系", @"上下游关系")]];
        [string1 replaceColorWithStr:@"＊" andColor:[UIColor redColor]];
        relationType.attributedText=string1;
        UIImageView *arrow1 = [UIImageView new];
        [relationTypeControl addSubview:arrow1];
        [arrow1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-16);
            make.height.mas_equalTo(12);
            make.width.mas_equalTo(12);
        }];
        arrow1.image = customerRelationImageName(@"ic_arrow_left");
        
        _relationTypeLable = [UILabel new];
        [relationTypeControl addSubview:_relationTypeLable];
        [_relationTypeLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(relationType).mas_equalTo(0);
            make.right.equalTo(arrow1.mas_left).mas_equalTo(-1);
            make.left.equalTo(relationType.mas_right).mas_equalTo(0);
        }];
        _relationTypeLable.font = font14;
        _relationTypeLable.textColor = FCGrayTxtPlaceColor;
        _relationTypeLable.textAlignment = NSTextAlignmentRight;
        _relationTypeLable.text = customerRelationLocaChanged(@"global_general_choose_please", @"请选择");
        
        // 分割线
        UIView *lineView = [UIView new];
        [_view addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(relationTypeControl.mas_bottom).mas_equalTo(0);
            make.left.and.right.mas_equalTo(0);
            make.height.mas_equalTo(1);
        }];
        
        lineView.backgroundColor = FCLineColor;
        
        // 指派企业联系人
        _relationEmployeeControl = [UIControl new];
        [_view addSubview:_relationEmployeeControl];
        [_relationEmployeeControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(relationTypeControl.mas_bottom).mas_equalTo(0);
            make.left.and.right.mas_equalTo(0);
            make.height.mas_equalTo(44);
        }];
        [_relationEmployeeControl addTarget:self action:@selector(relationEmployeeSelectAction) forControlEvents:UIControlEventTouchUpInside];
        UILabel *relationEmployee = [UILabel new];
        [_relationEmployeeControl addSubview:relationEmployee];
        [relationEmployee mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.centerY.mas_equalTo(0);
        }];
        relationEmployee.font = font14;
        relationEmployee.textColor = FCGrayTxtDetailColor;
        NSMutableAttributedString *string2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  ＊", customerRelationLocaChanged(@"指派企业联系人", @"指派企业联系人")]];
        [string2 replaceColorWithStr:@"＊" andColor:[UIColor redColor]];
        relationEmployee.attributedText = string2;
        UIImageView *arrow2 = [UIImageView new];
        [_relationEmployeeControl addSubview:arrow2];
        [arrow2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-16);
            make.height.mas_equalTo(12);
            make.width.mas_equalTo(12);
        }];
        arrow2.image = customerRelationImageName(@"ic_arrow_left");
        self.relationEmployeeValue = [UILabel new];
        [_relationEmployeeControl addSubview:_relationEmployeeValue];
        [_relationEmployeeValue mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(arrow2.mas_left).mas_equalTo(-1);
            make.centerY.mas_equalTo(0);
        }];
        _relationEmployeeValue.font = font14;
        _relationEmployeeValue.textColor = FCGrayTxtPlaceColor;
        _relationEmployeeValue.text = customerRelationLocaChanged(@"global_general_choose_please", @"请选择");
        
        _employeeScrollView = [FCChoiceEmpScrollView new];
        [_view addSubview:_employeeScrollView];
        [_employeeScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_relationEmployeeControl.mas_bottom).mas_equalTo(0);
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.height.mas_equalTo(70);
            make.bottom.mas_equalTo(-10);
        }];
        _employeeScrollView.backgroundColor = UIColor.whiteColor;
        _employeeScrollView.showEmpName = YES;
        
    }
    return self;
}

- (void)relationEmployeeSelectAction{
    NSDictionary *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:@"crmSupplyRelationOnlyTypeManager" parameters:nil];
    FCCrmSupplyRelationOnlyTypeManagerModel *relationOnlyTypeManagerModel = [FCCrmSupplyRelationOnlyTypeManagerModel mj_objectWithKeyValues: cache];
    UIViewController *con = [self.viewController pushAppControllerWithControllerName:@"FCChoiceEmployeeListViewController" andObjectData:@{@"nonChoicedArr":self.oldEmployeeArr, @"departGroupIdArr": relationOnlyTypeManagerModel.companyDepartmentId ? @[relationOnlyTypeManagerModel.companyDepartmentId] : @[]} andTitle:customerRelationLocaChanged(@"指派我司联系人", @"指派我司联系人")];
    
    WJCWeakSelf
    con.idBlock = ^(NSArray<FCEmployeeModel *> *employees) {
        weakSelf.oldEmployeeArr = employees;
        [weakSelf.employeeIdArr removeAllObjects];
        for (FCEmployeeModel *employeeModel in employees) {
            [weakSelf.employeeIdArr addObject:employeeModel.Id];
        }
        weakSelf.employeeScrollView.Employee = [NSMutableArray arrayWithArray:employees];
        if (weakSelf.employeeIdArr.count > 0) {
            _relationEmployeeValue.text = @"";
        } else{
            _relationEmployeeValue.text = customerRelationLocaChanged(@"global_general_choose_please", @"请选择");
        }
        // 返回选中的联系人
        if (weakSelf.employeeIdsBlock) {
            weakSelf.employeeIdsBlock(weakSelf.employeeIdArr);
        }
    };
}

- (void)layoutSubviews{
    [super layoutSubviews];
    BA_ViewBorderRadius(_view, 4, 0.5, FCEnableColor);
}

// 获取缓存数据
- (void)getCacheData{
    //获取缓存数据
    WJCWeakSelf
    if ([FCEmployeeModel empCompanyIsMine]) {
        self.manageRelationTypes = [NSMutableArray array];
    } else {
        NSMutableDictionary *relationTypeParam = [NSMutableDictionary dictionary];
        relationTypeParam[@"isManage"] = @"YES";
        NSArray *manageRelationTypeCache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:relationTypeParam];
        self.manageRelationTypes = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:manageRelationTypeCache];
    }
    
    NSArray *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:nil];
    self.relationTypes = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:cache];
    if (self.relationTypes.count && self.manageRelationTypes.count) {
        [self showRelationTypeSelect];
    } else {
        if (!self.isLoadData) {
            
            [self getRelationType];
        }
    }
}

- (void)getRelationType{
    self.isLoadData = YES;
    
    NSNumber *take = @(15);
    NSDictionary *args = @{@"enable": @(YES),
                           @"take": take,
                           @"skip": @(self.relationTypes.count)
                           };
    
    WJCWeakSelf
    [FCCustomerRelationRequest getCrmSupplyRelationTypeWithArgs:args success:^(id resultObj) {
        FCRelationTypeListModel *relationTypesModel = [FCRelationTypeListModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationTypes"]];
        [weakSelf.relationTypes addObjectsFromArray:relationTypesModel.items];
        if (weakSelf.relationTypes.count >= relationTypesModel.pageInfo.total) {
            XMGLog(@"relationType 全部请求完成");
            weakSelf.isLoadData = NO;
            //缓存
            NSArray *cache = [FCRelationTypeModel mj_keyValuesArrayWithObjectArray:self.relationTypes];
            [FCFuChengCacheTool saveHttpCache:cache urlString:FCCrmSupplyRelationTypesDataKey parameters:nil];
            
            [self showRelationTypeSelect];
        } else {
            XMGLog(@"relationType 继续请求");
            [self getRelationType];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        XMGLog(@"%@", error);
        self.isLoadData = NO;
    }];
}

- (void)showRelationTypeSelect{
    WJCWeakSelf
    FCRelationTyleSheetViewController *sheetVC = [[FCRelationTyleSheetViewController alloc] init];
    sheetVC.relationTypeArr = self.relationTypes;
    sheetVC.priorityRelationTypeArr = self.manageRelationTypes;
    sheetVC.selectedRelationTypeArr = self.selectedRelationTypeArr;
    sheetVC.completeBlock = ^(NSMutableArray<FCRelationTypeModel *> * _Nonnull selectedRelationTypes) {
        weakSelf.selectedRelationTypeArr = selectedRelationTypes;
        
        NSString *typeStr = @"";
        [weakSelf.relationTypeIdArr removeAllObjects];
        for (FCRelationTypeModel *typeModel in selectedRelationTypes) {
            XMGLog(@"%@",typeModel.name);
            typeStr = [NSString stringWithFormat:@"%@、%@",typeStr, typeModel.name];
            [weakSelf.relationTypeIdArr addObject:typeModel.Id];
        }
        if (typeStr.length > 1) {
            typeStr = [typeStr substringFromIndex:1];
        }
        if (typeStr.length > 0) {
            weakSelf.relationTypeLable.text = typeStr;
            weakSelf.relationTypeLable.textColor = FCTxtColor;
        } else{
            weakSelf.relationTypeLable.text = customerRelationLocaChanged(@"global_general_choose_please", @"请选择");
            weakSelf.relationTypeLable.textColor = FCGrayTxtPlaceColor;
        }
        
        // 返回选中的relationType
        if (weakSelf.relationTypeIdsBlock) {
            weakSelf.relationTypeIdsBlock(weakSelf.relationTypeIdArr);
        }
    };
    sheetVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    sheetVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    [SVProgressHUD dismiss];
    [self.viewController presentViewController:sheetVC animated:YES completion:^{ }];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

